package com.leetcode.common;

/**
 * 链表节点模型类
 * 为了其他地方都能以一样的方式使用，修改类属性和构造方法为public
 *
 * @author fy
 * @date 2022/4/16 22:02
 */
public class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    /**
     * 增加通过数组构造链表头结点的构造函数
     *
     * @param nums
     */
    public ListNode(int[] nums) {
        if (nums == null || nums.length == 0) {
            throw new RuntimeException("wrong nums");
        }
        this.val = nums[0];
        ListNode cur = this;
        for (int i = 1; i < nums.length; i++) {
            cur.next = new ListNode(nums[i]);
            cur = cur.next;
        }
    }

    /**
     * 覆盖toString方法, 可以通过头结点打印整个链表
     *
     * @return
     */
    @Override
    public String toString() {
        ListNode cur = this;
        StringBuilder sb = new StringBuilder();
        while (cur != null) {
            sb.append(cur.val).append("->");
            cur = cur.next;
        }
        sb.append("null");
        return sb.toString();
    }
}
/* *** 力扣ListNode定义 ***/
/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */